package com.shawn.baseappbygroovydsl.utils

import android.content.Context
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import com.allenliu.versionchecklib.callback.APKDownloadListener
import com.allenliu.versionchecklib.v2.AllenVersionChecker
import com.allenliu.versionchecklib.v2.builder.NotificationBuilder
import com.allenliu.versionchecklib.v2.builder.UIData
import com.allenliu.versionchecklib.v2.callback.ForceUpdateListener
import com.shawn.baseappbygroovydsl.R
import java.io.File


object UtilVersion : LifecycleObserver {

    fun checkVersionUpdate(appContext: Context, downLoadUrl:String,newestVersionCode:Int,apkDownloadListener: APKDownloadListener?,
                           forceUpdateListener:ForceUpdateListener?,
                           lifecycle: Lifecycle?) {
        lifecycle?.addObserver(this)
        AllenVersionChecker
            .getInstance()
            .downloadOnly(UIData.create())
            .setDirectDownload(true)
            .setDownloadUrl(downLoadUrl)
            .setApkDownloadListener(apkDownloadListener)
            .setForceUpdateListener(forceUpdateListener)
            .setNewestVersionCode(newestVersionCode)
            .setShowDownloadingDialog(false)
            .setShowDownloadFailDialog(false)
            .setDownloadAPKPath(createDownLoadPath(appContext))
            .setForceRedownload(false)
            .setShowNotification(false)
            .setNotificationBuilder(
                NotificationBuilder.create()
                    .setRingtone(true)
                    .setIcon(R.mipmap.ic_girl)
                    .setTicker("正在下载")
                    .setContentTitle(appContext.getString(R.string.app_name))
                    .setContentText("正在下载资源文件...")
            )
            .setRunOnForegroundService(true)
            .executeMission(appContext)
    }

    private fun createDownLoadPath(context: Context): String {
        val appCachePath = context.filesDir.absolutePath + "/AllenVersionPath/"
        val file = File(appCachePath)
        if (!file.exists()) {
            file.mkdirs()
        }
        return appCachePath
    }

    @OnLifecycleEvent(value = Lifecycle.Event.ON_DESTROY)
    private fun clear() {
        AllenVersionChecker.getInstance().cancelAllMission()
    }

}